package net.xinshi.commons;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.CookieStore;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author <a href="mailto:liukuo@xinshi.net">liukuo</a>
 * @version 1.0
 * @description
 * @since 2017/6/28.
 */
public class HttpUtil {
    @Autowired
    public static HttpClientManager452 httpClientManager;

    public HttpClientManager452 getHttpClientManager() {
        return httpClientManager;
    }

    public void setHttpClientManager(HttpClientManager452 httpClientManager) {
        HttpUtil.httpClientManager = httpClientManager;
    }

    private static ResponseHandler<byte[]> newDefaultResponseHandler() {
        return new ResponseHandler<byte[]>() {
            public byte[] handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
                HttpEntity entity = response.getEntity();
                if (entity != null) {
                    return EntityUtils.toByteArray(entity);
                } else {
                    return null;
                }
            }
        };
    }

    public static String post(String url, JSONObject jRequestData, Cookie[] cookies, HttpServletRequest request, HttpServletResponse httpServletResponse) throws Exception {
        HttpPost post = new HttpPost(url);
        List<NameValuePair> postData = new ArrayList<NameValuePair>();
        if (jRequestData != null) {
            for (Map.Entry<String, Object> entry : jRequestData.entrySet()) {
                postData.add(new BasicNameValuePair(entry.getKey(), entry.getValue().toString().trim()));
            }
        }
        UrlEncodedFormEntity entity = new UrlEncodedFormEntity(postData, "UTF-8");
        post.setEntity(entity);
        CloseableHttpClient httpClient = httpClientManager.getHttpClient();
        StringBuilder str = new StringBuilder();
        if (cookies != null && cookies.length > 0) {
            for (Cookie cookie : cookies) {
                str.append(cookie.getName()).append("=").append(cookie.getValue()).append(";");
            }
        }
        String sessionId = request.getHeader("sessionId");
        if(StringUtils.isNotBlank(sessionId)){
            str.append("isid=").append(sessionId).append(";");
        }
        post.setHeader("Cookie", str.toString());
        String responseContent = null;
        CloseableHttpResponse response = null;
        try {
            HttpClientContext context = HttpClientContext.create();
            context.setCookieStore(new BasicCookieStore());//将httpClient里的cookie清除
            response = httpClient.execute(post, context);//执行post请求
            CookieStore cookieStore = context.getCookieStore();//获取cookieStore
            List<org.apache.http.cookie.Cookie> cookiess = cookieStore.getCookies();//获取服务端返回的所有的cookie
            StringBuilder sb = new StringBuilder();//拼接cookie
            for (org.apache.http.cookie.Cookie cookie : cookiess) {
                sb.append(cookie.getName()).append("=").append(cookie.getValue()).append(";");
                httpServletResponse.addHeader("Set-Cookie", cookie.getName() + "=" + cookie.getValue() + ";Path=/;HttpOnly");
            }
            httpServletResponse.addHeader("Cookie", sb.toString());//将cookie设置到响应头里
            HttpEntity responseEntity = response.getEntity();//获取返回值
            responseContent = EntityUtils.toString(responseEntity, "UTF-8");//将返回值转成string
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                // 关闭连接,释放资源
                if (response != null) {
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return responseContent;
    }

}
